package com.example.wang_yi_homework4;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    Button btnBindService, btnUnbindService, btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind = false;
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            serviceBinder = (MyService.MyServiceBinder) iBinder;
            isServiceBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            isServiceBind = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnBindService = findViewById(R.id.btnBindService);
        btnUnbindService = findViewById(R.id.btnUnbindService);
        btnGetStatus = findViewById(R.id.btnGetStatus);
        tvServiceStatus = findViewById(R.id.tvServiceStatus);

        btnBindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                if (!isServiceBind) {
                    bindService(intent, conn, BIND_AUTO_CREATE);
                    tvServiceStatus.setText("当前服务状态: 已连接");
                }
            }
        });

        btnGetStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isServiceBind && serviceBinder != null) {
                    tvServiceStatus.setText("当前服务状态: " + serviceBinder.getCount());
                }
                else {
                    tvServiceStatus.setText("当前服务状态: 尚未连接");
                }
            }
        });

        btnUnbindService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isServiceBind) {
                    unbindService(conn);
                    isServiceBind = false;
                    tvServiceStatus.setText("当前服务状态: 已断开");
                }
            }
        });
    }
}